﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.IO;
using System.Threading;
using System.Net;

using CommonLib;
using Hik.Communication.Scs.Communication.EndPoints.Tcp;
using Hik.Communication.Scs.Communication.Messages;
using Hik.Communication.Scs.Server;

namespace TrackingServerService
{
    public partial class TrackingServerService : ServiceBase
    {
        private delegate void UpdateStatusCallback(string strMessage);

        private string address;

        public TrackingServerService()
        {
            InitializeComponent();

            if (!System.Diagnostics.EventLog.SourceExists("TrackingLogSourse"))
                System.Diagnostics.EventLog.CreateEventSource("TrackingLogSourse", "TrackingLog");
            eventLogMsg.Source = "TrackingLogSourse";
            eventLogMsg.Log = "TrackingLog";
        }

        #region Initialize start listenning

        private string GetIP()
        {
            string strHostName = "";
            strHostName = System.Net.Dns.GetHostName();

            IPHostEntry ipEntry = System.Net.Dns.GetHostEntry(strHostName);

            IPAddress[] addr = ipEntry.AddressList;

            return addr[addr.Length - 1].ToString();
        }

        //private void StartListening()
        //{
        //    eventLog1.WriteEntry("Tracking service started in " + ipString);

        //    // Parse the server's IP address out of the TextBox
        //    IPAddress ipAddr = IPAddress.Parse(ipString);
        //    // Create a new instance of the ChatServer object
        //    TrackingServer mainServer = new TrackingServer(ipAddr);
        //    // Hook the StatusChanged event handler to mainServer_StatusChanged
        //    TrackingServer.StatusChanged += new StatusChangedEventHandler(mainServer_StatusChanged);
        //    // Start listening for connections
        //    mainServer.StartListening();

        //    // Show that we started to listen for connections
        //    eventLog1.WriteEntry(ipString + " is monitoring for connections ...");
        //}

        #endregion

        #region New Initialize listenting

        private IScsServer server;
        private void StartListening()
        {
            string address = GetIP() + ":10033";

            eventLogMsg.WriteEntry("Tracking service started in " + address);

            server = ScsServerFactory.CreateServer(new ScsTcpEndPoint(address));

            server.WireProtocolFactory = new TrackingWireProtocolFactory(); //Set custom wire protocol factory!
            server.ClientConnected += server_ClientConnected;

            server.Start();
        }

        private void server_ClientConnected(object sender, ServerClientEventArgs e)
        {
            //Console.WriteLine("A new client is connected. Address: " + e.Client.RemoteEndPoint);
            eventLogMsg.WriteEntry("A new client is connected. Address: " + e.Client.RemoteEndPoint);
            e.Client.MessageReceived += Client_MessageReceived;
        }

        private void Client_MessageReceived(object sender, MessageEventArgs e)
        {
            //Console.WriteLine("A client sent a message: " + ((TrackingDataMessage)e.Message).ToString());
            eventLogMsg.WriteEntry("A client sent a message: " + ((TrackingDataMessage)e.Message).ToString());
        }

        #endregion

        protected override void OnStart(string[] args)
        {
            StartListening();
        }

        //private void UpdateStatus(string strMessage)
        //{
        //    // Updates the log with the message
        //    eventLog1.WriteEntry(strMessage);
        //}

        protected override void OnStop()
        {
            eventLogMsg.WriteEntry("Tracking Server stopped");
            server.Stop();
            //timer1.Enabled = false;
            //TextWriter file = new StreamWriter("C:\\logfile1.txt", true);
            //file.WriteLine("Service stopped");
            //file.Close();

            //stateTimer.Dispose();
        }

        //private void timer1_Tick(object sender, System.EventArgs e)
        //{
        //    TextWriter file = new StreamWriter("C:\\logfile1.txt", true);
        //    file.WriteLine("CPU Usage: " + performanceCounter1.NextValue().ToString() + " " + System.DateTime.Now.ToString());
        //    file.Close();
        //}
    }
}
